package com.company.beauty.common.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * <p></p >
 *
 * @author youyoukele
 * @version 1.0
 * @date 2023/9/22 15:41
 */
@Slf4j
public class LarkNotificationUtil {

    /**
     * 飞书机器人告警
     *
     * @param webhookUrl
     * @param user
     * @param title
     * @param messageBody
     * @return
     * @throws Exception
     */
    public static String sendLarkNotification(String webhookUrl, String user, String title, String messageBody) throws Exception {
        URL url = new URL(webhookUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

        ObjectMapper mapper = new ObjectMapper();
        ObjectNode root = mapper.createObjectNode();
        ObjectNode content = root.putObject("content").putObject("post").putObject("zh_cn");
        content.put("title", title);

        ArrayNode contentArray = content.putArray("content");
        ArrayNode atUserArray = contentArray.addArray();
        atUserArray.addObject().put("tag", "at").put("user_id", user);

        ArrayNode messageArray = contentArray.addArray();
        messageArray.addObject().put("tag", "text").put("text", messageBody);

        root.put("msg_type", "post");

        byte[] input = mapper.writeValueAsBytes(root);

        try (OutputStream os = connection.getOutputStream()) {
            os.write(input, 0, input.length);
        }

        try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                response.append(line);
            }
            return response.toString();
        }
    }

}
